package models

import (
	"errmsg"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/fwhezfwhez/errorx"
	"time"
	"tools"
)

type Trip struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`             // 用户id
	What       string `orm:"column(what)" json:"what" form:"what"`                      // 做什么
	Time       string `orm:"column(time)" json:"time" form:"time"`                      // 提醒时间
	Date       string `orm:"column(date)" json:"date" form:"date"`                      // 提醒日期
	Wkocc      string `orm:"column(wkocc)" json:"wkocc" form:"wkocc"`                   // 循环
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"` // 存放时间
	Status     int64  `orm:"column(status)" json:"status" form:"status"`
	To         string `orm:"column(to)" json:"to" form:"to"`                      // 提醒对象
	IsFinish   int64  `orm:"column(is_finish)" json:"is_finish" form:"is_finish"` // 是否完成
	Source     string `orm:"column(source)" json:"source" form:"source"`          // 提醒来源
	ToUser     *User  `orm:"-" json:"to_user"`
}

func (m *Trip) TableName() string {
	return "trip"
}

func init() {
	orm.RegisterModel(new(Trip))
}

func NewTrip() *Trip {
	return &Trip{}
}

func GetTrip() []*Trip {
	var (
		t        time.Time
		currTime string
		currData string
		week     int
		start    int
		end      int
		ls       []*Trip
		reg      string
		sql      string
		err      error
		num      int64
	)

	t = time.Now()
	currTime = t.Format("15:04")
	currData = t.Format("2006-01-02")
	week = tools.GetWeekDay()

	start = week;
	end = 6 - week;
	ls = []*Trip{}

	reg = fmt.Sprintf("[01]{%d}1[01]{%d}", start, end);
	sql = "select * from `trip` where `status` = 1 and `is_finish` = 0 and `time` = ? and (`wkocc` REGEXP ? or (`wkocc` = \"0000000\" and `date` = ?))"

	if num, err = orm.NewOrm().Raw(sql, currTime, reg, currData).QueryRows(&ls); err != nil {
		logs.Error("GetTrip error:", errorx.New(err))
		return nil
	}
	if num == 0 {
		return nil
	}

	for k, v := range ls {
		ls[k].ToUser, _ = GetUserById(v.To)
	}

	return ls
}

func SetTripFinish(t *Trip) error {
	t.IsFinish = 1
	// 数据入库
	if _, err := orm.NewOrm().Update(t); err != nil {
		logs.Error("SetTripFinish error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}
